﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.IO;
using System.Threading;

namespace DirectoryMonitor
{
    class monitorPath
    {
        public string pathToMonitor;
        public decimal monitorInterval;

        public class CurrentState
        {
            public DateTime lastChecked;
            public string mostRecentFile;
        }

        public void checkForNewFiles(BackgroundWorker worker, DoWorkEventArgs e)
        {
            CurrentState state = new CurrentState();
            DateTime lastCheckDateTime = DateTime.Now;

            state.lastChecked = lastCheckDateTime;

            if (Directory.Exists(this.pathToMonitor))
            {
                while (true)
                {
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                        break;
                    }
                    // This path is a directory
                    // Process the list of files found in the directory. 
                    string[] fileNames = Directory.GetFiles(this.pathToMonitor, "*.jpg");
                    DateTime[] lastwriteTimes = new DateTime[fileNames.Length];
                    DateTime[] creationTimes = new DateTime[fileNames.Length];
                    for (int i = 0; i < fileNames.Length; i++)
                        lastwriteTimes[i] = new FileInfo(fileNames[i]).LastWriteTime;
                    Array.Sort(lastwriteTimes, fileNames);


                    if (fileNames.Length > 0)
                    {
                        state.mostRecentFile = fileNames[fileNames.Length - 1];
                        worker.ReportProgress(0, state);
                    }

                    //Thread.Sleep(1000);
                    Thread.Sleep((Int32)this.monitorInterval * 1000);
                    
                }
            }
            else
            {
                throw new Exception("Directory not found");
            }

        }

    }
}
